<?php
/**
 * Created by PhpStorm.
 * User: ZhangWei
 * Date: 2018/2/26
 * Time: 16:01
 */

namespace App\Http\Controllers\Api\Open;


use App\Http\Resources\Material as MaterialResources;
use App\Http\Resources\MaterialCollection;
use App\Logic\MaterialLogic;
use App\Models\Material;
use Illuminate\Http\Request;

class MaterialController extends BaseController
{

    public function index(Request $request)
    {
        $user = $this->getUser();
        $type = $request->input("type", false);
        $material = Material::query()->where('user_id', $user->id)->orderByDesc('id');
        if ($type) {
            $material->where('type', $type);
        }
        $page = $material->paginate(10);
        $data['list'] = new MaterialCollection($page);
        return $this->success($data);
    }

    public function uploadImage(Request $request)
    {
        $user = $this->getUser();
        list($state, $obj) = MaterialLogic::upLoadImage($request, $user);
        if ($state) {
            $material = new MaterialResources($obj);
            return $this->success($material);
        } else {
            return $this->failed($obj);
        }
    }

    public function uploadAudio(Request $request)
    {
        $user = $this->getUser();
        list($state, $obj) = MaterialLogic::uploadAudio($request, $user);
        if ($state) {
            $material = new MaterialResources($obj);
            return $this->success($material);
        } else {
            return $this->failed($obj);
        }
    }

    public function uploadVideo(Request $request)
    {
        $user = $this->getUser();
        list($state, $obj) = MaterialLogic::uploadVideo($request, $user);
        if ($state) {
            $material = new MaterialResources($obj);
            return $this->success($material);
        } else {
            return $this->failed($obj);
        }
    }


    public function delete(Request $request)
    {
        $user = $this->getUser();
        $id = $request->input("id");
        $id = hashid_decode($id);
        $material = Material::query()->where('user_id', $user->id)->findOrFail($id);
        Material::del($material);
        return $this->message('删除成功');

    }


}